//
//  ImageDetailViewController.m
//  0.3camera
//
//  Created by 茶 on 2023/11/23.
//

#import "DetailViewController.h"
#import "CADetailCollectionViewCell.h"

@interface DetailViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;


@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initInterface];
}

- (void)initInterface {
    self.view.backgroundColor = UIColor.whiteColor;
    
    [self.view addSubview:self.collectionView];
    self.navigationItem.title = [NSString stringWithFormat:@"%ld/%ld", (_index + 1), self.dataSource.count];
    
    NSArray *imgNames = @[@"Detail_1", @"Detail_2", @"Detail_3", @"Detail_4"];
    NSMutableArray *btns = [NSMutableArray arrayWithCapacity:imgNames.count];
    
    for (int i = 0; i < imgNames.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i;
        [button setImage:[UIImage imageNamed:imgNames[i]] forState:UIControlStateNormal];
        [self.view addSubview:button];
        [btns addObject:button];
        [button addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_offset(25);
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-14);
        }];
    }
    [btns mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:25 leadSpacing:61.5 tailSpacing:61.5];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_index inSection:0];
    [_collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
    [self collectionView:_collectionView didSelectItemAtIndexPath:indexPath];
}

- (void)buttonEvent:(UIButton *)button{
    CASavedModel *model = self.dataSource[_index];
    UIImage *image = [UIImage imageWithContentsOfFile:model.imgPath];
    NSUInteger tag = button.tag;
    if (tag == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    } else if (tag == 1) {
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    } else if (tag == 2) {
        CAWeakify(self);
        [LEEAlert alert].config
        .LeeTitle(@"提示")         // 添加一个标题 (默认样式)
        .LeeContent(@"确实删除选中图片？")        // 添加一个标题 (默认样式)
        .LeeCancelAction(@"取消", ^{        //添加一个默认类型的Action (默认样式 字体颜色为蓝色)
        })
        .LeeAction(@"确定", ^{    // 添加一个取消类型的Action (默认样式 alert中为粗体 actionsheet中为最下方独立)
            CAStrongify(self);
            [self.dataSource removeObjectAtIndex:self.index];
            [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.index inSection:0]]];
            [[NSFileManager defaultManager] removeItemAtPath:model.imgPath error:nil];
            if (self.deleteBlock) {
                self.deleteBlock();
            }
        })
        .LeeShow();
    } else if (tag == 3) {
        [self shareEventWithImage:image];
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = nil ;
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    [self.view makeToast:msg];
    NSLog(@"+++++++++++%@", msg);
}

- (void)shareEventWithImage:(UIImage *)image {
    UIImage *shareImg = image;
    NSArray *activityItems = [[NSArray alloc] initWithObjects:shareImg, nil];
    UIActivityViewController *activity = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    UIPopoverPresentationController *popover = activity.popoverPresentationController;
    if (popover) {
        popover.sourceView = self.view;
        popover.permittedArrowDirections = UIPopoverArrowDirectionUp;
    }
    [self presentViewController:activity animated:YES completion:NULL];
    CAWeakify(self);
    activity.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        CAStrongify(self);
        if (completed) {
            [self.view makeToast:@"分享成功"];
        }
    };
}


- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    CADetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kImageDetailIdentifier forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSIndexPath *currentIndexPath = [self.collectionView indexPathForItemAtPoint:scrollView.contentOffset];
    if (currentIndexPath) {
        _index = currentIndexPath.row;
        self.navigationItem.title = [NSString stringWithFormat:@"%ld/%ld", (currentIndexPath.row + 1), self.dataSource.count];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = self.view.bounds.size;
        layout.sectionInset = UIEdgeInsetsZero;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = HexColor(@"#F8F8F8");
        [_collectionView registerClass:[CADetailCollectionViewCell class] forCellWithReuseIdentifier:kImageDetailIdentifier];
        _collectionView.pagingEnabled = YES;
        _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _collectionView.showsHorizontalScrollIndicator = NO;
    }
    return _collectionView;
}
@end
